package util

import (
	"context"
	"errors"
	"gitee.com/goddesszz/gocommon/myutil"
	"github.com/minio/minio-go/v7"
	"github.com/sirupsen/logrus"
	"mime/multipart"
	"monoblog/config"
	"strings"
	"time"
)

func UploadPicture(objectName string, file *multipart.FileHeader) (string, error) {
	contentType := file.Header.Get("Content-Type")

	// 检查文件类型是否为图片
	if !strings.HasPrefix(contentType, "image/") {
		return "", errors.New("file type is not image")
	}

	open, err := file.Open()
	if err != nil {
		logrus.Errorf("open file %s failed: %v", file.Filename, err)
		return "", err
	}
	defer open.Close()

	linkUrl, err := UploadByReader(objectName, contentType, open, file.Size)

	// 从返回的url中截取到基础路径
	i := strings.Index(linkUrl, "?")
	if i != -1 {
		linkUrl = Substring(linkUrl, 0, i)
	}
	return linkUrl, err
}

func UploadByReader(objectName string, contentType string, file multipart.File, fileSize int64) (string, error) {
	ctx := context.Background()
	// 存放图片的bucket
	bucketName := "blog-picture"

	minioClient := config.GetMinioClient()

	info, err := minioClient.PutObject(ctx, bucketName, objectName, file, fileSize, minio.PutObjectOptions{ContentType: contentType})
	if err != nil {
		logrus.Errorf("upload file %s to minio failed: %v", objectName, err)
		return "", err
	}

	logrus.Infof("Successfully uploaded %s . info: %s", objectName, myutil.JsonToString(info))

	url, err := minioClient.PresignedGetObject(ctx, bucketName, objectName, 24*time.Hour, nil)
	if err != nil {
		logrus.Errorf("get minio file url failed: %v", err)
		return "", err
	}
	logrus.Infof("get minio file success. url: %s", url.String())

	return url.String(), nil
}

func UploadByFile(objectName string, contentType string, filePath string) (string, error) {
	ctx := context.Background()
	// 存放图片的bucket
	bucketName := "blog-picture"

	minioClient := config.GetMinioClient()

	// Upload the test file with FPutObject
	info, err := minioClient.FPutObject(ctx, bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
	if err != nil {
		logrus.Errorf("upload file %s to minio failed: %v", objectName, err)
		return "", err
	}

	logrus.Infof("Successfully uploaded %s . info: %s", objectName, myutil.JsonToString(info))

	url, err := minioClient.PresignedGetObject(ctx, bucketName, objectName, 24*time.Hour, nil)
	if err != nil {
		logrus.Errorf("get minio file url failed: %v", err)
		return "", err
	}
	logrus.Infof("get minio file success. url: %s", url.String())

	return url.String(), nil
}
